import { jsPDF } from "jspdf";
import html2canvas from "html2canvas";

export const savePdf = (dom: string, fileName: string) => {
  // 判断所有图片是否都已经转成base64了，如果没有继续等待
  // 我在模板的所有图片的onload里在转base64，每转成一个就调取下载方法，
  // 下载方法就判断是否和要生成的图片总数一致
  // let imgload = this.judgeimg();
  // if (!imgload) {
  //   return false;
  // }
  const pdf = new jsPDF("", "pt", "a4");
  let pdfList = document.getElementsByClassName(dom);
  for (let i = 0, len = pdfList.length; i < len; i++) {
    let target = pdfList[i];
    // target.style.background = "#FFFFFF";
    html2canvas(target).then(function (canvas) {
      const contentWidth = canvas.width;
      const contentHeight = canvas.height;

      //一页pdf显示html页面生成的canvas高度;
      const pageHeight = (contentWidth / 595.28) * 841.89;
      //未生成pdf的html页面高度
      let leftHeight = contentHeight;
      //页面偏移
      let position = 0;
      //a4纸的尺寸[595.28,841.89]，html页面生成的canvas在pdf中图片的宽高
      const imgWidth = 595.28;
      const imgHeight = (592.28 / contentWidth) * contentHeight;

      const pageData = canvas.toDataURL("image/jpeg", 1.0);
      if (leftHeight < pageHeight) {
        pdf.addImage(pageData, "JPEG", 0, 0, imgWidth, imgHeight);
        // 为下一条数据添加空白页
        if (i < len - 1) {
          pdf.addPage();
        }
      } else {
        while (leftHeight > 0) {
          pdf.addImage(pageData, "JPEG", 0, position, imgWidth, imgHeight);
          leftHeight -= pageHeight;
          position -= 841.89;
          //避免添加空白页
          if (leftHeight > 0) {
            pdf.addPage();
          }
        }
      }
      if (i === len - 1) {
        pdf.save(`${fileName}.pdf`);
      }
    });
  }
};
